<template>
  <div class="home">
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>网页截图</span>
        </div>
      </template>
      
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="目标URL" prop="url">
          <el-input 
            v-model="form.url" 
            placeholder="请输入完整的网页URL，例如：https://www.example.com"
            :disabled="loading"
            @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <el-form-item label="图片尺寸" required>
          <el-row :gutter="10">
            <el-col :span="11">
              <el-form-item prop="width" :error="widthError">
                <el-input-number 
                  v-model="form.width" 
                  :min="1" 
                  :max="10000" 
                  :disabled="loading"
                  controls-position="right"
                  placeholder="宽度"
                />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="text-center">x</el-col>
            <el-col :span="11">
              <el-form-item prop="height" :error="heightError">
                <el-input-number 
                  v-model="form.height" 
                  :min="1" 
                  :max="10000"
                  :disabled="loading" 
                  controls-position="right"
                  placeholder="高度"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSubmit" 
            :loading="loading"
            :disabled="!form.url"
          >
            {{ loading ? '截图中...' : '开始截图' }}
          </el-button>
          <el-button @click="resetForm" :disabled="loading">重置</el-button>
        </el-form-item>

        <!-- 进度提示 -->
        <el-form-item v-if="loading">
          <el-progress 
            :percentage="progress" 
            :status="progressStatus"
            :format="progressFormat"
            :stroke-width="15"
            :show-text="true"
          />
          <div class="progress-tip">{{ progressTip }}</div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 结果预览 -->
    <el-card v-if="taskResult" class="result-card">
      <template #header>
        <div class="card-header">
          <span>截图结果</span>
          <div class="operations">
            <el-button 
              type="primary" 
              link 
              @click="handleDownload"
              :disabled="!previewUrl"
            >
              下载图片
            </el-button>
            <el-button 
              type="primary" 
              link 
              @click="handleRetry"
              v-if="taskResult.status === 3"
            >
              重试
            </el-button>
          </div>
        </div>
      </template>

      <!-- 错误状态 -->
      <div v-if="taskResult.status === 3" class="error-container">
        <el-alert
          :title="taskResult.errorMsg || '截图失败'"
          type="error"
          show-icon
          :closable="false"
        />
      </div>

      <!-- 预览图片 -->
      <div v-else class="preview-container">
        <el-image 
          :src="previewUrl" 
          :preview-src-list="previewUrl ? [previewUrl] : []"
          fit="contain"
          loading="lazy"
          class="preview-image"
        >
          <template #placeholder>
            <div class="image-placeholder">
              <el-icon><Picture /></el-icon>
              <span>加载中...</span>
            </div>
          </template>
          <template #error>
            <div class="image-placeholder">
              <el-icon><Warning /></el-icon>
              <span>加载失败</span>
            </div>
          </template>
        </el-image>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Warning } from '@element-plus/icons-vue'
import screenshotApi from '../api/screenshot'

const formRef = ref(null)
const loading = ref(false)
const taskResult = ref(null)
const previewUrl = ref('')
const progress = ref(0)
let checkTimer = null
let progressTimer = null

const form = ref({
  url: '',
  width: 1920,
  height: 1080,
  format: 'jpg',
  quality: 90,
  captureMode: 'full'
})

const rules = {
  url: [
    { required: true, message: '请输入URL', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入URL'))
        } else if (!/^https?:\/\/.+/.test(value)) {
          callback(new Error('请输入完整的URL，必须包含 http:// 或 https://'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  width: [
    { required: true, message: '请输入宽度', trigger: 'blur' },
    { type: 'number', min: 1, max: 10000, message: '宽度必须在1-10000之间', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入高度', trigger: 'blur' },
    { type: 'number', min: 1, max: 10000, message: '高度必须在1-10000之间', trigger: 'blur' }
  ]
}

const progressStatus = computed(() => {
  if (!taskResult.value) return '';
  return taskResult.value.status === 3 ? 'exception' : 'success';
})

const progressFormat = (percentage) => {
  if (!taskResult.value) return '准备中...';
  if (taskResult.value.status === 3) return '失败';
  if (taskResult.value.status === 2) return '完成';
  return '处理中...';
}

const progressTip = computed(() => {
  if (!taskResult.value) {
    return '正在准备截图环境...'
  }
  switch (taskResult.value.status) {
    case 0:
      return '正在等待处理...'
    case 1:
      return '正在加载页面并截图...'
    case 2:
      return '截图完成！'
    case 3:
      return '截图失败，请重试'
    default:
      return '处理中...'
  }
})

const startProgressAnimation = () => {
  progress.value = 0;
  progressTimer = setInterval(() => {
    if (progress.value < 90) {
      progress.value += 1;
    }
  }, 200);
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    taskResult.value = null
    previewUrl.value = ''
    startProgressAnimation()
    
    const response = await screenshotApi.createTask(form.value)
    const taskId = response.data.data.taskId
    
    // 开始轮询任务状态
    checkTimer = setInterval(async () => {
      try {
        const statusResponse = await screenshotApi.getTaskStatus(taskId)
        const status = statusResponse.data.data
        
        if (status.status === 2) { // 成功
          clearInterval(checkTimer)
          clearInterval(progressTimer)
          progress.value = 100
          loading.value = false
          taskResult.value = status
          // 获取预览图片
          const imageResponse = await screenshotApi.getTaskResult(taskId)
          previewUrl.value = URL.createObjectURL(new Blob([imageResponse.data]))
          ElMessage.success('截图完成')
        } else if (status.status === 3) { // 失败
          clearInterval(checkTimer)
          clearInterval(progressTimer)
          progress.value = 100
          loading.value = false
          taskResult.value = status
          ElMessage.error(status.errorMsg || '截图失败')
        }
      } catch (error) {
        console.error('Status check error:', error)
        // 如果是网络错误，继续轮询
        if (!error.response) return
        
        // 如果是服务器错误，停止轮询
        clearInterval(checkTimer)
        clearInterval(progressTimer)
        progress.value = 100
        loading.value = false
        taskResult.value = {
          status: 3,
          errorMsg: error.response?.data?.message || '检查任务状态失败'
        }
        ElMessage.error('检查任务状态失败')
      }
    }, 1000)
    
  } catch (error) {
    loading.value = false
    clearInterval(progressTimer)
    console.error('Error:', error)
    ElMessage.error(error.response?.data?.message || '提交失败')
  }
}

const handleDownload = () => {
  if (!previewUrl.value) return
  const link = document.createElement('a')
  link.href = previewUrl.value
  link.download = `screenshot.${form.value.format}`
  link.click()
}

const handleRetry = () => {
  taskResult.value = null
  previewUrl.value = ''
  handleSubmit()
}

const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  taskResult.value = null
  previewUrl.value = ''
  progress.value = 0
}

onUnmounted(() => {
  if (checkTimer) {
    clearInterval(checkTimer)
  }
  if (progressTimer) {
    clearInterval(progressTimer)
  }
  if (previewUrl.value) {
    URL.revokeObjectURL(previewUrl.value)
  }
})
</script>

<style scoped>
.home {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
}

.result-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background: #f5f7fa;
  border-radius: 4px;
}

.preview-image {
  max-width: 100%;
  max-height: 600px;
}

.text-center {
  text-align: center;
  line-height: 32px;
}

.error-container {
  padding: 20px 0;
}

.image-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #909399;
}

.image-placeholder :deep(.el-icon) {
  font-size: 32px;
  margin-bottom: 10px;
}

.operations {
  display: flex;
  gap: 10px;
}

.progress-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 14px;
  text-align: center;
}

:deep(.el-progress-bar__inner) {
  transition: width 0.3s ease;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
}

.form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.result-card {
  margin-top: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 